<template>
	 <view class="chat">
	    <!-- ... 其他顶部和滚动视图代码 ... -->
	    <scroll-view :style="{height: `${windowHeight-inputHeight - 180}rpx`}"
	                 id="scrollview"
	                 scroll-y="true" 
	                 :scroll-top="scrollTop"
	                 class="scroll-view">
	      <!-- 聊天主体 -->
	      <view class="chat-body">
	          <!-- 聊天记录 -->
	          <view v-for="(item, index) in msgList" :key="index">
	          <!-- 自己发的消息 -->
	          <view class="item self" v-if="item.userContent != ''">
	            <!-- 文字内容 -->
	            <view class="content right">
	              {{ item.userContent }}
				 <view v-if="item.isvoice===true" class="audio-icon-me" tabindex="0"></view>
	            </view>
	            <!-- 头像 -->
	            <image class="avatar" :src="item.image"></image>
	          </view>
	          <!-- 机器人发的消息 -->
	          <view class="item Ai" v-if="item.botContent != ''">
	            <image class="avatar" :src="item.image"></image>
	            <view class="content left">
	              {{ item.botContent }}
	              <!-- 卡片内容应该放在这里 -->
	              <view v-if="item.card" class="card">
	                <view class="card-content">
	                  <text>{{ item.card.title }}</text>
	                  <input type="text" v-model="cardInput" placeholder="内容均由AI输出,仅供参考" />
	                  <button @click="handleCardAction(item.card.buttonAction)">去挂号</button>
					  <button @click="rehandleCardAction(item.card.buttonAction)">重新挂号</button>
	                </view>
	              </view>
	            </view>
	          </view>
		  <!-- 发送语音动画 -->
          <view v-if="isSendingVoice" class="send-voice-animation">
            <view class="voice-wave">
              <view class="wave" v-for="n in 3" :key="n"></view>
            </view>
          </view>
        </view>
      </view>
	    </scroll-view>
		<!-- 底部消息发送栏 -->
		<view class="chat-bottom" :style="{height: `${inputHeight}rpx`}">
			<view class="send-msg" :style="{bottom:`${keyboardHeight - 60}rpx`}">
        <view class="uni-textarea">
		<view class="startVoiceRecognition">
				<view :class="['mic-layer',{'mic-layer-talking':isTalking}]">
					<!-- 按钮样式 -->
					<view :class="isTalking?'mic-btn-talking':'mic-btn'" @touchstart="touchStart" @touchend="onEnd" @longpress="onStart"  @touchmove="handleRecordMove">
						<view v-show="!isTalking" class="record-button">
							<text class="">语音</text>
						</view>
						<view v-show="isTalking" class="mic-btn-talking_text">说话中...</view>
						<view v-show="isTalking&&!sendLock" class="tip-text"><text class="mr-10">松开</text>发送</view>
					</view>
					<!-- 语音音阶动画 -->
					<view v-if="isTalking" :class="['record-animate-box',{'active':sendLock}]">
						<view class="voice-scale">
							<view class="item" v-for="(item,index) in 10" :key="index"></view>
						</view>
					</view>
					<!-- 取消发送 -->
					<view v-if="isTalking":class="['record-cancel',{'active':sendLock}]">
						<text class="close-icon">x</text>
						<view class="tip-text" v-show="sendLock"><text class="mr-10">松开</text>取消</view>
					</view>
				</view>
				 <!-- 发送语音动画 -->
				<view v-show="isTalking && !sendLock" class="send-voice-animation" ref="sendVoiceAnimation">
				    <!-- 发送语音动画 -->
				    <view class="voice-wave">
				      <view class="wave" v-for="n in 3" :key="n"></view>
				    </view>
			  </view>
			</view>
          <textarea v-model="chatMsg"
            maxlength="300"
            confirm-type="send"
            @confirm="handleSend"
            placeholder="快来聊天吧~"
            :show-confirm-bar="false"
            :adjust-position="false"
            @linechange="sendHeight"
            @focus="focus" @blur="blur"
           auto-height></textarea>
        </view>
				<button @click="handleSend" class="send-btn">发送</button>
			</view>
		</view>
	</view>
</template>
<script>
export default {
  data() {
    return {
      isTalking: false,
	  isSendingVoice: false, 
      sendLock: false,
	  cardInput: '',
      record: null,
      startPoint: {},
      keyboardHeight: 0,
      bottomHeight: 0,
      scrollTop: 0,
      userId: '',
      chatMsg: "",
	  isRecording: false,
	  voiceDuration: 0,
	  voiceUrl: '',
      robotReplies: {
        '不知道挂什么科': '您好，请问有什么不适症状或者具体的疾病吗？',
        '头疼': '请问是持续性还是偶尔性发生？',
        '偶尔': '是否还有其他症状',
        '没有': {
          text: '通过你的回答和相关症状，建议你优先到以下科室挂号。',
          card: {
            title: "建议挂号",
            description: "根据您的描述，建议您到内科进行挂号。",
            buttonText: "去挂号",
            buttonAction: "/pages/officeone/officeone"
          }
        },
        '肚子疼': '请问疼痛的部位是哪里？',
        '腹部': '请问持续性还是偶尔发生',
        '持续性': '请问持续多久了？',
        '3天': '通过你的回答和相关症状，建议你优先到以下科室挂号。',
        '咳嗽': '是否还有其他症状',
        '流鼻涕': '通过你的回答和相关症状，建议你优先到以下科室挂号。'
      },
      msgList: [
        {
          botContent: "hi~我是AI导诊助手小智，你有任何用药问题都可以向我提问哦~",
          userContent: "",
          image: "/static/xiaozhi.png",
		  isvoice:false
        },
        {
          botContent: "",
          userContent: "你好呀，非常高兴认识你",
          image: "/static/头像/头像.jpg",
		  isvoice:false
        },
      ]
    }
  },
  watch: {
    msgList() {
      this.scrollToBottom();
    }
  },
  computed: {
    windowHeight() {
      return this.rpxTopx(uni.getSystemInfoSync().windowHeight);
    },
    inputHeight() {
      return this.bottomHeight + this.keyboardHeight;
    }
  },
  onLoad() {
    this.record = uni.getRecorderManager();
    uni.onKeyboardHeightChange(res => {
      this.keyboardHeight = this.rpxTopx(res.height);
      if (this.keyboardHeight < 0) this.keyboardHeight = 0;
    });
  },
  onUnload() {
    uni.offKeyboardHeightChange();
  },
  methods: {
	    // 开始录音
	    startRecord() {
	      this.isRecording = true;
	      this.voiceDuration = 0;
	      const options = {
	        duration: 60000, 
	        sampleRate: 44100, 
	        numberOfChannels: 1,
	      };
	      this.record.start(options);
	    },
	    
	    // 停止录音并发送
	    stopRecord() {
			console.log("现在停止录音了");
			this.isRecording = false;
			this.isTalking = false;
			
			this.record.stop();
			 // this.record.onStop(res => {
	  //       this.voiceUrl = res.tempFilePath;
	        // this.voiceDuration = Math.ceil(res.duration / 1000);
	        this.msgList.push({
			   botContent: "",
			   userContent: "     2\"",
			   image: "/static/common/unname2.jpg",
			   isvoice:true
	        });
			console.log("已添加聊天记录");
	        this.scrollToBottom();
	    },
	    
	    playVoice(voiceUrl) {
	      uni.playVoice({
	        filePath: voiceUrl
	      });
	    },
    onStart() {
      const option = {
        format: 'mp3'
      };
      this.isTalking = true;
      uni.vibrateShort();
      this.record.start(option);
      this.record.onStart(res => {
        console.log('start', res);
      });
      this.record.onError(res => {
        console.log('录音错误事件：', res);
      });
    },
   onEnd() {
	 // console.log("已停止录音！");

	   this.stopRecord();
     
     this.record.onStop(res => {
       console.log(res, "录音回调地址");
       if (this.sendLock) {
         this.sendLock = false;
         console.log('取消发送');
         return;
       }
       if (res.duration < 100) {
         uni.showToast({
           icon: 'error',
           title: '说话时间太短'
         });
         return;
       }
       // 调用启动发送语音动画的方法
       this.startSendVoiceAnimation();
     });
   },

	startSendVoiceAnimation() {
	  this.$nextTick(() => {
	    // 显示发送语音动画
	    this.$refs.sendVoiceAnimation.classList.add('active');
	    // 动画持续时间
	    setTimeout(() => {
	      // 隐藏发送语音动画
	      this.$refs.sendVoiceAnimation.classList.remove('active');
	      // 这里可以添加发送语音的逻辑
	      this.sendVoice();
	    }, 1000); // 动画持续1秒
	  });
	},
	   sendVoice() {
	     console.log('发送语音');
	     this.isSendingVoice = true;
	     // 动画持续时间，这里假设为2秒
		   this.msgList.push({ isSendingVoice: true });
	     setTimeout(() => {
	       // 动画结束，隐藏发送语音动画
	       this.isSendingVoice = false;
	       // 添加语音发送逻辑
	     }, 2000); // 动画持续2秒
	   },
    touchStart(e) {
      this.startPoint.clientX = e.changedTouches[0].clientX;
      this.startPoint.clientY = e.changedTouches[0].clientY;
    },
	//获取当前触摸点的信息
    handleRecordMove(e) {
      let touchData = e.touches[0];
      let moveX = touchData.clientX - this.startPoint.clientX;
      let moveY = touchData.clientY - this.startPoint.clientY;
      if (moveY > -45) {
        this.sendLock = false;
      } else {
        this.sendLock = true;
      }
    },
        goback() {
          uni.switchTab({
            url: "/pages/demo/demo"
          });
        },
        focus() {
          this.scrollToBottom();
        },
        blur() {
          this.scrollToBottom();
        },
        rpxTopx(px) {
          let deviceWidth = uni.getSystemInfoSync().windowWidth;
          let rpx = (750 / deviceWidth) * Number(px);
          return Math.floor(rpx);
        },
        sendHeight() {
          setTimeout(() => {
            let query = uni.createSelectorQuery();
            query.select('.send-msg').boundingClientRect();
            query.exec(res => {
              this.bottomHeight = this.rpxTopx(res[0].height);
            });
          }, 10);
        },
        scrollToBottom() {
          setTimeout(() => {
            let query = uni.createSelectorQuery().in(this);
            query.select('#scrollview').boundingClientRect();
            query.select('#msglistview').boundingClientRect();
            query.exec((res) => {
              if (res[1].height > res[0].height) {
                this.scrollTop = this.rpxTopx(res[1].height - res[0].height);
              }
            });
          }, 50);
        },
        handleCardAction(action) {
              if (action) {
                console.log('用户输入的卡片内容:', this.cardInput);
                uni.navigateTo({
                  url: action
                });
              }
            },
			rehandleCardAction(action) {
			      if (action) {
			        console.log('用户输入的卡片内容:', this.cardInput);
			        uni.navigateTo({
			          url: '/pages/room/room'
			        });
			      }
			    },
       
        simulateRobotChat(userInput) {
          userInput = userInput.trim();
          let reply = this.robotReplies[userInput] || this.robotReplies['默认'];
          return reply;
        },
        handleSend() {
          if (!this.chatMsg || /^\s+$/.test(this.chatMsg)) {
            uni.showToast({
              icon: 'none',
              title: '不能发送空白消息'
            });
            return;
          }
          this.msgList.push({
            botContent: "",
            userContent: this.chatMsg,
            image: "/static/common/unname2.jpg"
          });
          this.chatMsg = '';
          this.scrollToBottom();
          setTimeout(() => {
            const lastUserInput = this.msgList[this.msgList.length - 1].userContent;
            const replyInfo = this.simulateRobotChat(lastUserInput);
            if (replyInfo.card) {
              this.msgList.push({
                botContent: replyInfo.text,
                userContent: "",
                image: "/static/xiaozhi.png",
                card: replyInfo.card
              });
            } else {
              this.msgList.push({
                botContent: replyInfo,
                userContent: "",
                image: "/static/xiaozhi.png"
              });
            }
            this.scrollToBottom();
          }, 1000);
        },
      }
    }
</script>

<style lang="scss" scoped>
	
	$chatContentbgc: #C2DCFF;
	$sendBtnbgc: #4F7DF5;
	/* 定义音频图标的初始样式 */
	.audio-icon-me {
	  display: inline-block;
	  width: 24px;
	  height: 24px;
	  background-image: url('/static/语音.png');
	  background-size: cover;
	  cursor: pointer;
	  position: relative;
	  overflow: hidden;
	}
	
	/* 定义动画 */
	@keyframes voiceWave {
	  0%, 100% {
	    transform: scale(0.5);
	  }
	  50% {
	    transform: scale(1);
	  }
	}
.audio-icon-me:hover {
  animation: voiceWave 0.5s linear infinite;
}
	 .voice {
	    display: flex;
	    align-items: center;
	    padding: 10rpx 20rpx;
	  
	    .voice-content {
	      display: flex;
	      align-items: center;
	      justify-content: center;
	      width: 200rpx;
	      height: 80rpx;
	      background-color: #f1f1f1;
	      border-radius: 40rpx;
	      margin: 0 20rpx;
	  
	      .voice-duration {
	        margin-right: 10rpx;
	      }
	  
	      .voice-icon {
	        width: 40rpx;
	        height: 40rpx;
	      }
	    }
	  }
	.wave {
	  width: 20px;
	  height: 20px;
	  background-color: #007aff;
	  border-radius: 50%;
	  animation: wave 1s infinite; // 应用波浪动画
	}
	
	@keyframes wave {
	  0%, 100% {
	    transform: scale(1);
	  }
	  50% {
	    transform: scale(0.5);
	  }
	}

	.topbox{
			.title{
				position: absolute;
				left: 98px;
				top: 16px;
				width: 190px;
				height: 63px;
				opacity: 1;
				
				font-family: Source Han Sans;
				font-size: 36px;
				font-weight: normal;
				line-height: normal;
				letter-spacing: 0em;
				
				font-variation-settings: "opsz" auto;
				font-feature-settings: "kern" on;
				color: #0256FF;
			}
			position: absolute;
			left: 0px;
			top: 0px;
			width: 375px;
			height: 95px;
			opacity: 1;
			
			background: #E0EAFF;
			
		}
		

	view,button,text,input,textarea {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}
 
	/* 聊天消息 */
	.chat {
     .topTabbar {
          width: 100%;
          height: 90rpx;
          line-height: 90rpx;
          display: flex;
          margin-top: 80rpx;
          justify-content: space-between;
      
          .icon {
            margin-left: 20rpx;
          }
      
          .text {
            margin: auto;
            font-size: 16px;
            font-weight: 700;
          }
      
          .button {
            width: 10%;
            margin: auto 20rpx auto 0rpx;
          }
        }
		.scroll-view {
			::-webkit-scrollbar {
					    display: none;
					    width: 0 !important;
					    height: 0 !important;
					    -webkit-appearance: none;
					    background: transparent;
					    color: transparent;
					  }
			
			background-color: #F6F6F6;
			
			.chat-body {
				display: flex;
				flex-direction: column;
				padding-top: 23rpx;
				.self {
					justify-content: flex-end;
				}
				.item {
					display: flex;
					padding: 23rpx 30rpx;
 
					.right {
						background-color: $chatContentbgc;
					}
					.left {
						background-color: #FFFFFF;
					}
                    // 聊天消息的三角形
					.right::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						left: 100%;
						top: 10px;
						border: 12rpx solid transparent;
						border-left: 12rpx solid $chatContentbgc;
					}
 
					.left::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						top: 10px;
						right: 100%;
						border: 12rpx solid transparent;
						border-right: 12rpx solid #FFFFFF;
					}
                   #scrollview {
                     height: 100%; /* 或者具体的px值 */
                     overflow-y: auto;
                   }
					.content {
						position: relative;
						max-width: 486rpx;
						border-radius: 8rpx;
						word-wrap: break-word;
						padding: 24rpx 24rpx;
						margin: 0 24rpx;
						border-radius: 5px;
						font-size: 32rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #333333;
						line-height: 42rpx;
					}
 
					.avatar {
						display: flex;
						justify-content: center;
						width: 78rpx;
						height: 78rpx;
						background: $sendBtnbgc;
						border-radius: 50rpx;
						overflow: hidden;
						
						image {
							align-self: center;
						}
 
					}
				}
			}
		}
 
		/* 底部聊天发送栏 */
		.chat-bottom {
		  width: 100%;
		  height: 100rpx;
		  background: #F4F5F7;
		  transition: all 0.1s ease;
		
		 .send-msg {
		   display: flex;
		   align-items: center; /* 垂直居中 */
		   padding: 16rpx 30rpx;
		   width: 100%;
		   min-height: 177rpx;
		   position: fixed;
		   bottom: 0;
		   background: #fff;
		   transition: all 0.1s ease;
		
		    .uni-textarea {
		      padding-bottom: 100rpx;
		      textarea {
		        width: 537rpx;
				left:60rpx;
		        min-height: 75rpx;
		        max-height: 500rpx;
		        background: #f1f1f1;
		        border-radius: 40rpx;
		        font-size: 32rpx;
		        font-family: PingFang SC;
		        color: #333333;
		        line-height: 74rpx;
		        padding: 5rpx 8rpx;
		        text-indent: 30rpx;
		      }
		    }
		
		    .send-btn {
		      display: flex;
		      align-items: center;
		      justify-content: center;
		      margin-bottom: 100rpx;
		      margin-left: 80rpx;
		      width: 120rpx;
		      height: 75rpx;
		      background: #1373E9;
		      border-radius: 50rpx;
		      font-size: 28rpx;
		      font-family: PingFang SC;
		      font-weight: 500;
		      color: #FFFFFF;
		      line-height: 28rpx;
		    }
		  }
		}
		 }
		.mr-10 {
		  margin-right: 10rpx;
		}
		
		.mic-layer {
		  width: 85rpx;
		  height: 75rpx; 
		  margin-left: -10px; 
		  position: fixed;
		  margin-bottom: 40rpx;
		  bottom: 30rpx;
		  width: 100%;
		  box-sizing: border-box;
		  .record-button {
		    width: 80rpx; 
		    border-radius: 50rpx; 
		    background-color: #2878F4;
		    color: #FFFFFF;
		    height: 80rpx;
		    line-height: 80rpx;
		    text-align: center;
		  }
		}

		 /* 讲话中样式 */
		 	.mic-layer-talking{
		 		position: fixed;
		 		width: 100vw;
		 		height: 100vh;
		 		left: 0;
		 		top: 0;
		 		background-color: rgba(0, 0, 0, .6);
		 		.mic-btn-talking{
		 			position: absolute;
		 			bottom: 0;
		 			width: 100vw;
		 			height: 200rpx;
		 			border-radius: 80px 80px 0 0;
		 			background-color: #F2F2F2;
		 			&_text{
		 				color: #999999;
		 				padding: 60rpx 0;
		 				text-align: center;
		 			}
		 		}
		/* 发送、取消提示文字 */
				.tip-text{
					position: absolute;
					top: -60rpx;
					left: 50%;
					width: 160rpx;
					text-align: center;
					transform: translateX(-50%);
					color: #E3E4EA;
					font-size: 24rpx;
				}
		/* 上方语音动画 */
				.record-animate-box{
					position: absolute;
					left: 50%;
					top: 50%;
					transform: translate(-50%,-50%);
					width: 300rpx;
					height: 140rpx;
					background-color: #2878F4;
					border-radius: 28rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					transition: all .3s;
					&.active{
						background-color: #f56c6c;
						width: 140rpx;
					}}
		/* 语音音阶 */
					.voice-scale {
						width: 60%;
						height: 40rpx;
						display: flex;
						align-items: center;
						justify-content: space-between;
						.item {
							display: block;
							background: #333333;
							width: 4rpx;
							height: 10%;
							margin-right: 2.5px;
							float: left;
							&:last-child{
								margin-right: 0px;
							}
							&:nth-child(1) {
								animation: load 1s 0.8s infinite linear;
							}
						
							&:nth-child(2) {
								animation: load 1s 0.6s infinite linear;
							}
						
							&:nth-child(3) {
								animation: load 1s 0.4s infinite linear;
							}
						
							&:nth-child(4) {
								animation: load 1s 0.2s infinite linear;
							}
						
							&:nth-child(5) {
								animation: load 1s 0s infinite linear;
							}
						
							&:nth-child(6) {
								animation: load 1s 0.2s infinite linear;
							}
						
							&:nth-child(7) {
								animation: load 1s 0.4s infinite linear;
							}
						
							&:nth-child(8) {
								animation: load 1s 0.6s infinite linear;
							}
						
							&:nth-child(9) {
								animation: load 1s 0.8s infinite linear;
							}
						
							&:nth-child(10) {
								animation: load 1s 1s infinite linear;
							}
						}
					}
	@keyframes load {
					0% {
						height: 10%;
					}
			
					50% {
						height: 100%;
					}
			
					100% {
						height: 10%;
					}
				}
			/* 取消按钮 */
					.record-cancel{
						position: absolute;
						left: 50%;
						bottom: 300rpx;
						transform: translateX(-50%);
						width: 100rpx;
						height: 100rpx;
						border-radius: 50%;
						background-color: rgba(0, 0, 0, .2);
						display: flex;
						justify-content: center;
						align-items: center;
						transition: all .3s;
						&.active{
							transform: translateX(-50%) scale(1.2);
							background-color: #f56c6c;
						}
						.close-icon{
							font-size: 40rpx;
							color: #FFFFFF;
						}
					}
		  }
		.send-voice-animation {
		  position: absolute;
		  bottom: 0;
		  left: 50%;
		  transform: translateX(-50%);
		  opacity: 0;
		  transition: opacity 0.5s;
		}
		
		.send-voice-animation.active {
		  opacity: 1;
		}
		
		.voice-wave {
		  display: flex;
		  justify-content: space-between;
		  width: 100px;
		}
		
		.wave {
		  width: 20px;
		  height: 20px;
		  background-color: #007aff;
		  border-radius: 50%;
		  animation: wave 1s infinite;
		}
		
		@keyframes wave {
		  0%, 100% {
		    transform: scale(1);
		  }
		  50% {
		    transform: scale(0.5);
		  }
		}
</style>